<?php

class Request {
	private $ApplicationName;
	private $ApplicationController;
	private $ApplicationDir;
	private $RunMethod;
	private $Parameters;
	private $Result;
	private $DisplayHandler;
	
	function __construct($AppName, $Method = null, $MethodParameters = null){
		
		$this->ApplicationName = strtolower($AppName);
		$this->RunMethod = ($Method != null) ? $Method : "init";
		$this->Parameters = $MethodParameters;
		
		$this->ApplicationDir = dirname(__FILE__)."/../lib/".$this->ApplicationName;
		$AppCoreFile = dirname(__FILE__)."/../lib/".$this->ApplicationName."/".$this->ApplicationName.".php";
		
		if(!is_dir($this->ApplicationDir) || !is_file($AppCoreFile)){
			throw new FMSException("Application < $this->ApplicationName > not found!", 2);
		}
		
		$this->DisplayHandler = new DisplayHandler($this);
	}
	
	function runApplication(){
		$AppCoreFile = dirname(__FILE__)."/../lib/".$this->ApplicationName."/".$this->ApplicationName.".php";
		
		require_once($AppCoreFile);
		
		$ApplicationControllerName = ucfirst($this->ApplicationName)."Controller";

		if(!class_exists($ApplicationControllerName)){
			throw new FMSException("Cannot find application < $ApplicationControllerName >", 2);
		}
		
		$this->ApplicationController = new $ApplicationControllerName();
		
		if(!($this->ApplicationController instanceof ApplicationController)){
			throw new FMSException("< $ApplicationControllerName > is not instance of ApplicationController.", 4);
		}
		
		if($this->ApplicationController->getStatus() != 0){
			throw new FMSException($this->ApplicationController->getErrorInfo(), 3);
		}
		
		$RunMethod = $this->RunMethod;
		
		$Parameters = (is_array($this->Parameters)) ? $this->Parameters : array($this->Parameters);
		
		$this->Result = $this->ApplicationController->$RunMethod($Parameters);

		
		$this->DisplayHandler->handle();
		
		return true;
	}
	
	function getApplicationName(){
		return $this->ApplicationName;
	}
	
	function getResult(){
		return $this->Result;
	}
	
	function setResult($result){
		$this->Result = $result;
	}
	
	function getApplicationController(){
		return $this->ApplicationController;
	}
	
	function getApplicationDir(){
		return $this->ApplicationDir;
	}
	
	function __toString(){
		if(empty($this->Result) || is_object($this->Result)){
			return "";
		}
		
		return $this->getResult();
	}
}

?>